package com.sky.service.impl;

import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.service.UserService;
import com.sky.utils.JwtUtil;
import com.sky.utils.WeChatUtil;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private WeChatUtil weChatUtil;

    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 微信登录
     */
    @Override
    public UserLoginVO wxLogin(UserLoginDTO userLoginDTO) {
        String code = userLoginDTO.getCode();
        
        // 调用微信接口获取openid
        String openid = weChatUtil.getOpenid(code);
        
        // 判断openid是否为空，为空表示登录失败
        if (openid == null) {
            throw new LoginFailedException("登录失败");
        }
        
        // 判断用户是否为新用户
        User user = userMapper.getByOpenid(openid);
        
        // 如果是新用户，则注册
        if (user == null) {
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }
        
        // 生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", user.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);
        
        // 构造返回结果

        return UserLoginVO.builder()
                .id(user.getId())
                .openid(user.getOpenid())
                .token(token)
                .build();
    }
}
